package edu.umn.contactviewer.task;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;

import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.util.Log;

import com.google.gson.Gson;

import edu.umn.contactviewer.Contact;
import edu.umn.contactviewer.constant.ContactViewerConstants;

public class GetContactsAsyncTask extends
		AsyncTask<String, Void, ArrayList<Contact>> {

	private static final String TAG = "GetContacts";
	private final Gson gson = new Gson();

	@Override
	protected ArrayList<Contact> doInBackground(String... arg0) {
		ArrayList<Contact> contacts = new ArrayList<Contact>();
		try {
			AndroidHttpClient client = AndroidHttpClient.newInstance("Android",
					null);
			HttpUriRequest request = new HttpGet(
					ContactViewerConstants.WEB_SERVICE_URL
							+ ContactViewerConstants.SEPARATOR_QUERY_STRING
							+ ContactViewerConstants.API_KEY_MAPPING);
			HttpResponse response = client.execute(request);
			InputStream in = response.getEntity().getContent();
			String jsonResponse = readJsonResponse(in);

			GetContactsResponseData getContactsResponseData = gson.fromJson(
					jsonResponse, GetContactsResponseData.class);
			if (null != getContactsResponseData.getContacts()) {
				contacts.addAll(getContactsResponseData.getContacts());
			}

			client.close();
			return contacts;

		} catch (IOException ex) {
			Log.e(TAG + "IO Exception: ", ex.toString());
		} catch (Exception ex) {
			Log.e(TAG + "Exception: ", ex.toString());
		}

		return contacts;
	}

	private String readJsonResponse(InputStream in) throws IOException {
		String jsonResponse = "";
		BufferedReader buffer = new BufferedReader(new InputStreamReader(in));
		String s = "";
		while ((s = buffer.readLine()) != null) {
			jsonResponse += s;
		}
		buffer.close();

		return jsonResponse;
	}
}
